/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package codegener.comp;

import codegener.entity.DsBean;
import codegener.util.JsonUtils;
import codegener.util.StrUtils;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author 32181
 */
public class DsJDialog extends javax.swing.JDialog {

    private List<DsBean> dss=null;
    private MFrame frame;
    /**
     * Creates new form DsJDialog
     */
    public DsJDialog(MFrame parent, boolean modal) {
        super(parent, modal);
        frame=parent;
        initComponents();
        init();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        dsTitle = new javax.swing.JComboBox<>();
        jLabel2 = new javax.swing.JLabel();
        dsType = new javax.swing.JComboBox<>();
        jLabel3 = new javax.swing.JLabel();
        dsUname = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        dsUpass = new javax.swing.JTextField();
        saveBtn = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        dbName = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        hostTxt = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        portTxt = new javax.swing.JTextField();
        testBtn = new javax.swing.JButton();

        jLabel7.setText("jLabel7");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("配置数据源");

        jLabel1.setText("数据源名称：");

        dsTitle.setEditable(true);
        dsTitle.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                dsTitleItemStateChanged(evt);
            }
        });

        jLabel2.setText("数据源类型：");

        dsType.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "MySQL", "Oracle", "达梦" }));
        dsType.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                dsTypeItemStateChanged(evt);
            }
        });

        jLabel3.setText("账号：");

        jLabel4.setText("密码：");

        saveBtn.setText(" 保  存 ");
        saveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveBtnActionPerformed(evt);
            }
        });

        jLabel5.setText("数据库：");

        jLabel6.setText("IP：");

        jLabel8.setText("端口：");

        testBtn.setText(" 测  试 ");
        testBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                testBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(105, 105, 105)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(testBtn)
                        .addGap(18, 18, 18)
                        .addComponent(saveBtn))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel8))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dsTitle, 0, 200, Short.MAX_VALUE)
                            .addComponent(dsType, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dsUname)
                            .addComponent(dsUpass)
                            .addComponent(dbName, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                            .addComponent(hostTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                            .addComponent(portTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE))))
                .addGap(118, 118, 118))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(57, 57, 57)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dsTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dsType, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dsUname, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(dsUpass, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(hostTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(portTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dbName, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(testBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(41, 41, 41))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveBtnActionPerformed
        // TODO add your handling code here:
        String title=String.valueOf(dsTitle.getSelectedItem());
        String type=String.valueOf(dsType.getSelectedItem());
        String uname=dsUname.getText()==null?"":dsUname.getText().trim();
        String upass=dsUpass.getText()==null?"":dsUpass.getText().trim();
        String dbname=dbName.getText()==null?"":dbName.getText().trim();
        String host=hostTxt.getText()==null?"":hostTxt.getText().trim();
        String port=portTxt.getText()==null?"":portTxt.getText().trim();
        
        DsBean ds=new DsBean();
        ds.setTitle(title);
        ds.setType(type);
        ds.setUname(uname);
        ds.setUpass(upass);
        ds.setDbname(dbname);
        ds.setHost(host);
        ds.setPort(port);
        save(ds);
    }//GEN-LAST:event_saveBtnActionPerformed

    private void testBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testBtnActionPerformed
        // TODO add your handling code here:
         String title=String.valueOf(dsTitle.getSelectedItem());
        String type=String.valueOf(dsType.getSelectedItem());
        String uname=dsUname.getText()==null?"":dsUname.getText().trim();
        String upass=dsUpass.getText()==null?"":dsUpass.getText().trim();
        String dbname=dbName.getText()==null?"":dbName.getText().trim();
        String host=hostTxt.getText()==null?"":hostTxt.getText().trim();
        String port=portTxt.getText()==null?"":portTxt.getText().trim();
        
        DsBean ds=new DsBean();
        ds.setTitle(title);
        ds.setType(type);
        ds.setUname(uname);
        ds.setUpass(upass);
        ds.setDbname(dbname);
        ds.setHost(host);
        ds.setPort(port);
        
        try(Connection conn=DriverManager.getConnection(ds.getUrl(), ds.getUname(), ds.getUpass())){
             if(conn.isValid(5000)){
                JOptionPane.showMessageDialog(this, "连接测试成功!");
             }else{
                JOptionPane.showMessageDialog(this, "连接测试失败!");
             }
        }catch(Exception e){
            JOptionPane.showMessageDialog(this, "连接测试失败!");
        }
        
    }//GEN-LAST:event_testBtnActionPerformed

    private void dsTitleItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_dsTitleItemStateChanged
        // TODO add your handling code here:
        
        String title=String.valueOf(dsTitle.getSelectedItem()==null?"":dsTitle.getSelectedItem());
        if(null!=title&&title.trim().length()>0){
            DsBean bean=getDsBean(title);
            if(null!=bean){
                dsType.setSelectedItem(bean.getType());
                dsUname.setText(bean.getUname());
                dsUpass.setText(bean.getUpass());
                hostTxt.setText(bean.getHost());
                portTxt.setText(bean.getPort());
                dbName.setText(bean.getDbname());
            }
            
        }
        
    }//GEN-LAST:event_dsTitleItemStateChanged

    private void dsTypeItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_dsTypeItemStateChanged
        // TODO add your handling code here:
        String item=(String)dsType.getSelectedItem();
        if("MySQL".equalsIgnoreCase(item)){
            portTxt.setText("3306");
        }
        if("oracle".equalsIgnoreCase(item)){
            portTxt.setText("1521");
        }
        if("达梦".equalsIgnoreCase(item)){
            portTxt.setText("5236");
        }
        if("dm".equalsIgnoreCase(item)){
            portTxt.setText("5236");
        }
        
    }//GEN-LAST:event_dsTypeItemStateChanged

    
    public List<DsBean> getDss(){
        return dss;
    }
    
    public DsBean getDsBean(String title){
        if(null!=dss&&!dss.isEmpty()){
            for(DsBean ds:dss){
                if(null!=ds&&null!=ds.getTitle()&&ds.getTitle().equals(title)){
                    return ds;
                }
            }
        }
        return null;
    }
    
    public void seletcedDsBean(DsBean ds){
        if(null!=dss&&!dss.isEmpty()){
            for(DsBean bean:dss){
                bean.setSelected(false);
            }
        }
        ds.setSelected(true);
    }
    
    private void init(){
        try{
            File conf=new File("./conf/dss.json");
            if(conf.exists()){
                DsBean selecteDsBean=null;
                String content=FileUtils.readFileToString(conf, "UTF-8"); 
                if(StrUtils.isNotBlank(content)){
                    List<Map<String,Object>> datas=JsonUtils.parseJsonToMaps(content);
                        if(null!=datas&&!datas.isEmpty()){
                            dss=new ArrayList<>();
                            for(Map<String,Object> data:datas){
                                DsBean dsBean=new DsBean();
                                dsBean.setTitle(String.valueOf(data.get("title")));
                                dsBean.setType(String.valueOf(data.get("type")));
                                dsBean.setUname(String.valueOf(data.get("uname")));
                                dsBean.setUpass(String.valueOf(data.get("upass")));
                                dsBean.setUrl(String.valueOf(data.get("url")));
                                dsBean.setDbname(String.valueOf(data.get("dbname")));
                                dsBean.setHost(String.valueOf(data.get("host")));
                                dsBean.setPort(String.valueOf(data.get("port")));
                                dsBean.setSelected(Boolean.valueOf(String.valueOf(data.get("selected"))));
                                dsTitle.addItem(dsBean.getTitle());
                                dss.add(dsBean);
                                
                                if(dsBean.isSelected()){
                                    selecteDsBean=dsBean;
                                }
                            }
                        }
                }
                
                if(null!=selecteDsBean){
                    dsType.setSelectedItem(selecteDsBean.getType());
                    dsUname.setText(selecteDsBean.getUname());
                    dsUpass.setText(selecteDsBean.getUpass());
                    hostTxt.setText(selecteDsBean.getHost());
                    portTxt.setText(selecteDsBean.getPort());
                    dbName.setText(selecteDsBean.getDbname());
                }
            }
            
            
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public void save(DsBean ds){
        File conf=new File("./conf/dss.json");
        if(!conf.getParentFile().exists()){
            conf.getParentFile().mkdir();
            
        }
        if(!conf.exists()){
            try{
               conf.createNewFile();
            }catch(Exception e){
                System.out.println("创建文件dss.json失败！");
                e.printStackTrace();
            }
        }
        if(conf.exists()){
            try{
                if(null==dss){
                    dss=new ArrayList<>();
                    dss.add(ds);
                }else{
                    if(!dss.isEmpty()){
                        DsBean bean=getDsBean(ds.getTitle());
                        if(null==bean){
                            bean=new DsBean();
                            dss.add(bean);
                        }
                        bean.setTitle(ds.getTitle());
                        bean.setUname(ds.getUname());
                        bean.setUpass(ds.getUpass());
                        bean.setDbname(ds.getDbname());
                        bean.setHost(ds.getHost());
                        bean.setPort(ds.getPort());
                        bean.setType(ds.getType());
                    }
                   
                }
                
                FileUtils.writeStringToFile(new File("./conf/dss.json"),JsonUtils.toJsonStr(dss), "UTF-8");
                frame.addDsMenu(ds.getTitle());
                dsTitle.addItem(ds.getTitle());
            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            System.out.println("dss.json文件不存在："+conf.getAbsolutePath());
        }
        this.setVisible(false);
    }
    
    public void showEditDialog(){
        if(null!=dss&&!dss.isEmpty()){
            DsBean bean=null;
            for(DsBean ds:dss){
                if(ds.isSelected()){
                    bean=ds;
                }
            }
            if(null!=bean){
                dsType.setSelectedItem(bean.getType()==null?"MySQL":bean.getType());
                dsUname.setText(bean.getUname()==null?"":bean.getUname());
                dsUpass.setText(bean.getUpass()==null?"":bean.getUpass());
                hostTxt.setText(bean.getHost()==null?"":bean.getHost());
                portTxt.setText(bean.getPort()==null?"3306":bean.getPort());
                dbName.setText(bean.getDbname()==null?"":bean.getDbname());
            }
        }
        
        setVisible(true);
    }
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField dbName;
    private javax.swing.JComboBox<String> dsTitle;
    private javax.swing.JComboBox<String> dsType;
    private javax.swing.JTextField dsUname;
    private javax.swing.JTextField dsUpass;
    private javax.swing.JTextField hostTxt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JTextField portTxt;
    private javax.swing.JButton saveBtn;
    private javax.swing.JButton testBtn;
    // End of variables declaration//GEN-END:variables
}
